import time
import requests


class TZnUtils:
    @staticmethod
    def getInfluxDatapoints( dpList , tableName , tags , fields):
        res = ""
        try:
            rows=[]
            for dp in dpList:
                tagList = [x +"="+ str(dp[x]) for x in tags]
                fieldList = [x +"="+ str(dp[x]) for x in fields]
                r = tableName
                r = r + "," + ",".join(tagList)
                r = r + " " + ",".join(fieldList)
                rows.append(r)
            if len(rows)>0:
                res = "\n".join(rows)
        except Exception as er:
            print(er)
        return  res

    @staticmethod
    def tm2str(tm = time.time()):
        resTm =""
        resDay = ""
        try:
            resDay = time.strftime('%Y%m%d', time.localtime(tm))
            resTm = time.strftime('%H%M%S', time.localtime(tm))
        except Exception as er:
            print(er)
        return resDay , resTm

    @staticmethod
    def write2InfluxDB(dpList , host , port , db , token  , tabName , tagFields , valueFields , rePolicy=''):
        resp = None
        try:
            if len(dpList)>0:
                datapointStr=''
                dps = []
                for dp in dpList:
                    dpTags =",".join([ t+"="+ dp[t] for t in tagFields])
                    dpFields =",".join([ f+"="+str(dp[f]) for f in valueFields])
                    item = tabName +","+dpTags+" "+dpFields
                    dps.append(item)
                datapointStr = "\n".join(dps)
                headers = {
                    "Authorization": token,
                    'Content-Type': 'application/json',
                }
                influxdb_url = "http://" + host + ":" + str(port) + '/write?db=' + db
                if rePolicy!='':
                    influxdb_url = influxdb_url +"&rp="+rePolicy
                resp = requests.post(url=influxdb_url, headers=headers, data=datapointStr)
        except Exception as er:
            print(er)
        return  resp